package priority_channel

import (
	"sync"
	"sync/atomic"
)

// memoryMonitor implements the MemoryMonitor interface
type memoryMonitor struct {
	currentUsage int64
	maxUsage     int64
	mu           sync.RWMutex
}

// newMemoryMonitor creates a new memory monitor
func newMemoryMonitor() MemoryMonitor {
	return &memoryMonitor{
		currentUsage: 0,
		maxUsage:     0,
	}
}

// GetMemoryUsage returns the current memory usage in bytes
func (mm *memoryMonitor) GetMemoryUsage() int64 {
	return atomic.LoadInt64(&mm.currentUsage)
}

// GetMaxMemoryUsage returns the maximum memory usage in bytes
func (mm *memoryMonitor) GetMaxMemoryUsage() int64 {
	mm.mu.RLock()
	defer mm.mu.RUnlock()
	return mm.maxUsage
}

// ResetMaxMemoryUsage resets the maximum memory usage counter
func (mm *memoryMonitor) ResetMaxMemoryUsage() {
	mm.mu.Lock()
	defer mm.mu.Unlock()
	mm.maxUsage = 0
}

// updateMemoryUsage updates the memory usage based on the number of events
// This is a simplified estimation - in a real implementation, you might want
// to use runtime.ReadMemStats() for more accurate memory tracking
func (mm *memoryMonitor) updateMemoryUsage(eventCount int) {
	// Estimate memory usage: each event is approximately 256 bytes
	// This is a rough estimation and should be adjusted based on actual measurements
	estimatedUsage := int64(eventCount * 256)

	atomic.StoreInt64(&mm.currentUsage, estimatedUsage)

	mm.mu.Lock()
	if estimatedUsage > mm.maxUsage {
		mm.maxUsage = estimatedUsage
	}
	mm.mu.Unlock()
}
